I have a slideshow:
<div (mousedown)="onMouseDown($event)"
(mousemove)="onMouseMove($event)"
(mouseup)="onMouseUp($event)">
<div class="swiper-wrapper">
<div *ngFor="let item of items; index as i;">
<custom-slide class="custom-slide"></custom-slide>
</div>
</div>
</div>
Methods onMouseDown, onMouseMove and onMouseUp are for dargging it using mouse.
The custom-slide Angular component listens to click events and pops up a dialog upon clicks.
But the problem is every time finish dragging the slideshow, a click event is always sent to a custom-slide component, therefore a dialog is popped up, which is what I want to avoid.
I tried to write the onMouseUp as below, but it doesn't work
onMouseUp() {
this.mouseIsDown = false;
const elements = document.getElementsByClassName("custom-slide");
if(this.isScrolling) {
for(let i = 0; i < elements.length; i++){
elements[i].addEventListener("click", this.preventClick);
}
} else {
for(let i = 0; i < elements.length; i++){
elements[i].removeEventListener("click", this.preventClick);
}
}
this.isScrolling = false;
}
preventClick(event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
Although in the preventClick method I prevented everything, but the slide can still receive the click event and pop up the dialog...
Could anyone teach me how to prevent it?
Thanks!
It depends...maybe You can catch event before custom-slide click event handler recives it if click event is on bubbling phase. then you can add your click-prevent listener on capturing phase which comes before bubbling phase
elements[i].addEventListener('click', this.preventClick, true);
specify third parameter as true (useCapture)
I used the following approach and it solved the problem:
in the slideshow component, which is where the mouseUp and mouseMove functions are located, keep a boolean variable indicating whether the user is dragging.
Then share this variable with the slide component via Emitter or some other ways.
I did it by placing both the variables and functions in a controller class, so I can share an instance of the class between the two components.
Then, in the slide component's click listener function, check if the variable is true, which means the user was dragging before releasing the left mouse button.
If yes, that means we want to ignore it, becase the user was dragging instead of clicking, and the click listener should return directly and do nothing.
If no, that means the user clicked it deliberately, then the listener function should keep finishing its job.